import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sleep_manager/data/family_info.dart';
import 'package:sleep_manager/globals.dart';
import 'package:sleep_manager/ui/home/home_page.dart';
import 'package:sleep_manager/ui/login/login_page.dart';

Future<void> main() async {

  // 确保WidgetsFlutterBinding初始化完成
  WidgetsFlutterBinding.ensureInitialized();

  // 确保 initApp 完成后再继续
  await initApp();

  runApp(const MyApp());

}

/// 初始化
Future<void> initApp() async {

  // 获取SharedPreferences实例，并使用globals.dart文件来存储静态变量
  final prefs = await SharedPreferences.getInstance();
  Globals.prefs = prefs;

  // 初始化Hive，注册适配器
  await Hive.initFlutter();
  Hive.registerAdapter(FamilyInfoAdapter());

  // 打开Box
  await Hive.openBox<FamilyInfo>('familyInfoBox');

}

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent, // 设置状态栏颜色透明
        statusBarBrightness: Brightness.dark, // 状态栏文本为黑色
        statusBarIconBrightness: Brightness.dark, // 状态栏图标也为黑色
      )
    );

    bool isLoggedIn = Globals.prefs?.getBool("isLoggedIn") ?? false;

    return MaterialApp(
      title: "睡眠监测",
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.transparent),
        useMaterial3: true,
      ),
      home: isLoggedIn ? const HomePage() : const LoginPage(),
    );
  }

}

